package com.ylyq.ylxx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylyq.ylxx.entity.*;
import com.ylyq.ylxx.lingo.ILingoService;
import com.ylyq.ylxx.model.ResponseData;
import com.ylyq.ylxx.model.bean.OceanengineUploadFileImage;
import com.ylyq.ylxx.model.bean.OceanengineUploadFileVideo;
import com.ylyq.ylxx.model.bean.ResultPlan;
import com.ylyq.ylxx.model.request.GeneratePlansRequest;
import com.ylyq.ylxx.model.request.LoginDTO;
import com.ylyq.ylxx.model.request.UploadFileImageRequest;
import com.ylyq.ylxx.model.request.UploadFileVideoRequest;
import com.ylyq.ylxx.quarz.JobServiceImpl;
import com.ylyq.ylxx.service.*;
import com.ylyq.ylxx.util.Tools;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.ini4j.Wini;
import org.quartz.JobDataMap;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName TestController
 * @Description TODO
 * @Author xiaweichao
 * @Date 2020/6/2 10:52
 * @Version 1.0
 */
@RestController
@RequestMapping("/test")
@Api(description = "测试模块")
public class TestController {
    @Value("${public.config.fileUploadPath}")
    private String fileUploadPath;
    @Value("${public.config.fileDownloadPath}")
    private String fileDownloadPath;
    @Autowired
    private JobServiceImpl jobService;
    @Autowired
    private IYlyqUserService sysUserService;
    @Autowired
    private IOceaneginePlanService iOceaneginePlanService;
    @Autowired
    private ICoreService iCoreService;
    @Autowired
    private IOceanengineToolService iOceanengineToolService;
    @Autowired
    private ILingoService iLingoService;
    @Autowired
    private IYlyqCreativeTitleV2Service iYlyqCreativeTitleV2Service;
    @Autowired
    private IYlyqGroupInfoService iYlyqGroupInfoService;
    @Autowired
    private IYlyqAudioService iYlyqAudioService;
    @Autowired
    private IFileService fileService;
    @Autowired
    private IYlyqTypeProductService iYlyqTypeProductService;
    @Autowired
    private IYlyqCreativeTagService iYlyqCreativeTagService;

    @PostMapping("/inputProduct")
    @ApiOperation(value = "输入产品")
    public ResponseData testPage(@RequestParam @ApiParam(value = "产品类型0表单，1鲁班，2直播", required = true) Integer productFlag,
                                 @RequestParam @ApiParam(value = "产品名称。", required = true) String productName,
                                 @RequestParam(required = false) @ApiParam(value = "人群关键词。多个用#分割") String renqun,
                                 @RequestParam(required = false) @ApiParam(value = "联想词。多个用#分割") String lianxiang,
                                 @RequestParam(required = false) @ApiParam(value = "产品属性。多个用#分割") String chanpin,
                                 @RequestParam(required = false) @ApiParam(value = "产品卖点词。多个用#分割") String chanpinSell,
                                 @RequestParam(required = false) @ApiParam(value = "产品竞品词。多个用#分割") String chanpinJp) {

        YlyqTypeProduct ylyqTypeProduct = new YlyqTypeProduct();
        ylyqTypeProduct.setTypeFlag(productFlag);
        ylyqTypeProduct.setProductName(productName);
        ylyqTypeProduct.setId(Tools.getUUID());
        iYlyqTypeProductService.save(ylyqTypeProduct);

//            0人群关键词 1联想词 2产品属性 3产品卖点词 4产品竞品词
        List<YlyqCreativeTag> ylyqCreativeTagList=new ArrayList<>();
        String[] split = renqun.split("#");
        for (String temp:split){
            YlyqCreativeTag ylyqCreativeTag=new YlyqCreativeTag();
            ylyqCreativeTag.setTagName(temp);
            ylyqCreativeTag.setTag_flag(0);
            ylyqCreativeTag.setProduct_id(ylyqTypeProduct.getId());
            ylyqCreativeTagList.add(ylyqCreativeTag);
        }
        String[] lianxiangList = lianxiang.split("#");
        for (String temp:lianxiangList){
            YlyqCreativeTag ylyqCreativeTag=new YlyqCreativeTag();
            ylyqCreativeTag.setTagName(temp);
            ylyqCreativeTag.setTag_flag(1);
            ylyqCreativeTag.setProduct_id(ylyqTypeProduct.getId());
            ylyqCreativeTagList.add(ylyqCreativeTag);
        }
        String[] chanpinList = chanpin.split("#");
        for (String temp:chanpinList){
            YlyqCreativeTag ylyqCreativeTag=new YlyqCreativeTag();
            ylyqCreativeTag.setTagName(temp);
            ylyqCreativeTag.setTag_flag(2);
            ylyqCreativeTag.setProduct_id(ylyqTypeProduct.getId());
            ylyqCreativeTagList.add(ylyqCreativeTag);
        }
        String[] chanpinSellList = chanpinSell.split("#");
        for (String temp:chanpinSellList){
            YlyqCreativeTag ylyqCreativeTag=new YlyqCreativeTag();
            ylyqCreativeTag.setTagName(temp);
            ylyqCreativeTag.setTag_flag(3);
            ylyqCreativeTag.setProduct_id(ylyqTypeProduct.getId());
            ylyqCreativeTagList.add(ylyqCreativeTag);
        }
        String[] chanpinJpList = chanpinJp.split("#");
        for (String temp:chanpinJpList){
            YlyqCreativeTag ylyqCreativeTag=new YlyqCreativeTag();
            ylyqCreativeTag.setTagName(temp);
            ylyqCreativeTag.setTag_flag(4);
            ylyqCreativeTag.setProduct_id(ylyqTypeProduct.getId());
            ylyqCreativeTagList.add(ylyqCreativeTag);
        }
        iYlyqCreativeTagService.inserBatch(ylyqCreativeTagList);

        return new ResponseData(ResponseData.Result.SUCCESS);
    }

    @PostMapping("/uploadAudio")
    @ApiOperation(value = "上传音乐背景素材", response = YlyqAreaOceangine.class)
    public ResponseData uploadAudio(@RequestParam("audioFlag") @ApiParam(value = "背景音乐对应的品类flag", required = true) Integer audioFlag, @RequestParam("file") MultipartFile file) {
        try {
            String fileUrl = fileService.uploadPhotoOrFile(file);
            if (StringUtils.isBlank(fileUrl))
                return new ResponseData(ResponseData.Result.FAIL);
            else {
                YlyqAudio ylyqAudio = new YlyqAudio();
                ylyqAudio.setAudioFlag(audioFlag);
                ylyqAudio.setAudioUrl(fileUrl.replace(fileDownloadPath, fileUploadPath));
                iYlyqAudioService.save(ylyqAudio);
                return new ResponseData(ResponseData.Result.SUCCESS, fileUrl);
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return new ResponseData(ResponseData.Result.FAIL);
        }
    }

    @PostMapping("/uploadFileScrapVideoWithAudio")
    @ApiOperation(value = "上传视频碎片素材带合成音乐", response = OceanengineUploadFileVideo.class)
    @ApiImplicitParams({@ApiImplicitParam(paramType = "header", dataType = "String", name = "content-type", value = "multipart/form-data", required = true)})
    public ResponseData uploadFileScrapVideoWithAudio(@RequestParam("advertiser_id") @ApiParam(value = "广告主ID", required = true) Long advertiser_id,
                                                      @RequestParam("count") @ApiParam(value = "生成计划数量") Long count,
                                                      @RequestParam("files1") @ApiParam(value = "视频文件,格式mp4、mpeg、3gp、avi（10s超时限制）", required = true) MultipartFile[] files1,
                                                      @RequestParam("files2") @ApiParam(value = "视频文件,格式mp4、mpeg、3gp、avi（10s超时限制）", required = true) MultipartFile[] files2,
                                                      @RequestParam("files3") @ApiParam(value = "视频文件,格式mp4、mpeg、3gp、avi（10s超时限制）", required = true) MultipartFile[] files3,
                                                      @RequestParam("files4") @ApiParam(value = "视频文件,格式mp4、mpeg、3gp、avi（10s超时限制）", required = true) MultipartFile[] files4,
                                                      @RequestParam("files5") @ApiParam(value = "视频文件,格式mp4、mpeg、3gp、avi（10s超时限制）", required = true) MultipartFile[] files5) {

        return iOceanengineToolService.uploadFileScrapVideoWithAudio(advertiser_id, count, files1, files2, files3, files4, files5);
    }

    @PostMapping("/uploadFileImage")
    @ApiOperation(value = "上传图片素材", response = OceanengineUploadFileImage.class)
    public ResponseData uploadFileImage(@RequestParam("advertiser_id") @ApiParam(value = "广告主ID", required = true) Long advertiser_id,
                                        @RequestParam(value = "upload_type") @ApiParam(value = "图片上传方式\\n\" +\n" +
                                                "            \"默认值：\\\"UPLOAD_BY_FILE\\\"\\n\" +\n" +
                                                "            \"允许值：\\\"UPLOAD_BY_FILE\\\"\\\"UPLOAD_BY_URL\\\"") String upload_type,
                                        @RequestParam(value = "image_signature", required = false) @ApiParam(value = "图片的md5值(用于服务端校验)，upload_type为\"UPLOAD_BY_FILE\"必填") String image_signature,
                                        @RequestParam(value = "image_url", required = false) @ApiParam(value = "图片url地址，如http://xxx.xxx，upload_type为\"UPLOAD_BY_URL\"必填") String image_url,
                                        @RequestParam(value = "filename", required = false) @ApiParam(value = "素材的文件名，可自定义素材名，不传择默认取文件名，最长255个字符\\n\" +\n" +
                                                "            \"注：若同一素材已进行上传，重新上传不会改名") String filename,
                                        @RequestParam(value = "file", required = false) @ApiParam(value = "图片文件,upload_type为\\\"UPLOAD_BY_FILE\\\"必填\\n\" +\n" +
                                                "            \"格式: jpg，jpeg,png,bmp,gif, 大小1M内") MultipartFile file) {

        UploadFileImageRequest uploadFileImageRequest = new UploadFileImageRequest(advertiser_id, upload_type, image_signature, image_url, filename, file);
        return iOceanengineToolService.uploadFileImage(uploadFileImageRequest);
//        return iOceanengineToolService.uploadFileImage(null);
    }

    @PostMapping("/uploadFileVideo")
    @ApiOperation(value = "上传视频素材", response = OceanengineUploadFileVideo.class)
    public ResponseData uploadFileVideo(@RequestParam("advertiser_id") @ApiParam(value = "广告主ID", required = true) Long advertiser_id,
                                        @RequestParam(value = "video_signature") @ApiParam(value = "视频的md5值(用于服务端校验)", required = true) String video_signature,
                                        @RequestParam(value = "filename", required = false) @ApiParam(value = "素材的文件名，可自定义素材名，不传择默认取文件名，最长255个字符\\n注：若同一素材已进行上传，重新上传不会改名") String filename,
                                        @RequestParam("file") @ApiParam(value = "视频文件,格式mp4、mpeg、3gp、avi（10s超时限制）", required = true) MultipartFile file) {

        UploadFileVideoRequest uploadFileVideoRequest = new UploadFileVideoRequest(advertiser_id, video_signature, filename, file);
        return iOceanengineToolService.uploadFileVideo(uploadFileVideoRequest);
    }

    @GetMapping("/refreshCore")
    @ApiOperation(value = "刷新打分表")
    public ResponseData refreshCore() {
        iCoreService.refreshCore();
        return new ResponseData(ResponseData.Result.SUCCESS);
    }

    @GetMapping("/refreshCity")
    @ApiOperation(value = "刷新城市表redis缓存")
    public ResponseData refreshCity() {
        iCoreService.refreshCity();
        return new ResponseData(ResponseData.Result.SUCCESS);
    }

    @PostMapping("/deleteAutoStopOrOpen")
    @ApiOperation(value = "删除一个自动启停规则")
    public ResponseData creatAutoStopOrOpen(String triggerName, String triggerGroup, String jobName, String jobGroup) {
        try {
//            JobDataMap jobDataMap = new JobDataMap();
//            jobDataMap.put("creatAutoStopOrOpen", loginDTO);
//            jobService.addJob("Job_Auto"+new Date().toString(),"JobAutoOpenOrClose","Trigger_Auto"+new Date().toString(),
//                    "TiggerAutoOpenOrClose",jobDataMap, TestTask.class,"0/3 * * * * ? ");
            jobService.deleteJob(triggerName, triggerGroup, jobName, jobGroup);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return new ResponseData(ResponseData.Result.SUCCESS);
    }

    @GetMapping("/test")
    public String test() throws FileNotFoundException {
        String temp = System.getProperty("user.dir") + "\\ylyq\\src\\main\\resources\\lingo\\lingosh.lng";
        String path = ResourceUtils.getURL("classpath:").getPath().replace("/target/classes", "") + "\\src\\main\\resources\\lingo\\lingosh.lng";
        return "temp==" + temp + "\npath====" + path;
    }

    @GetMapping("/test1")
    public String test1() {
        QueryWrapper<YlyqGroupInfo> groupInfoQueryWrapper = new QueryWrapper<>();
        List<YlyqGroupInfo> ylyqGroupInfos = iYlyqGroupInfoService.list();
        Map<Long, List<YlyqGroupInfo>> collectGroupList = ylyqGroupInfos.stream().collect(Collectors.groupingBy(YlyqGroupInfo::getGroupId));
        return new SimpleDateFormat("yyyy-MM-dd").format(collectGroupList.get(1678587665421341l).get(0).getCreatedTime());
    }

    @GetMapping("/index")
    public String index(Map<String, Object> map) {
        map.put("name", "美丽的天使...");
        return "index";
    }

    /**
     * @return com.ylyq.ylxx.model.ResponseData
     * @Author xiaweichao
     * @Description //TODO 测试mybatisplus的分页功能。 * @Date 16:46 2020/7/8
     * @Param []
     **/
    @ApiOperation(value = "获取所有用户")
    @GetMapping("/getAlluser")
    public ResponseData getAlluser() {

//        IPage<YlyqUser> page = new Page<>(1, 20);
//        IPage<YlyqUser> pageResult = sysUserService.page(page, null);
//        return new ResponseData(ResponseData.Result.SUCCESS,pageResult);不要使用这种方式，这样会反复查


//        List<YlyqUser> records = sysUserService.page(page).getRecords();
//        List<YlyqUser> records = sysUserService.page(new Page<>(1, 20)).getRecords();
//        return new ResponseData(ResponseData.Result.SUCCESS, records);
        return new ResponseData(ResponseData.Result.SUCCESS, sysUserService.page(new Page<>(1, 20), null));
    }


    @PostMapping("/generatePlans")
    @ApiOperation(value = "批量生成广告计划", response = ResultPlan.class)
    public ResponseData generatePlans(@Valid @RequestBody GeneratePlansRequest generatePlansRequest) {
        try {
            return iOceaneginePlanService.generatePlans(generatePlansRequest);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(ResponseData.Result.FAIL);
        }
    }

    @PostMapping("/testLingo")
    @ApiOperation(value = "testLingo", response = ResultPlan.class)
    public ResponseData testLingo() {
        try {
//            StringBuilder parms = new StringBuilder();
//            parms.append("2~\n");
//            parms.append("2~\n");
//
//            //产品定价 高 高中 中端 中低 低
//            parms.append("3~\n");
//            //获取产品打分值
////                String path = ResourceUtils.getURL("classpath:").getPath().replace("/target/classes", "") + "\\src\\main\\resources\\lingo\\lingoproduct.lng";
////                String path = System.getProperty("user.dir")+ "\\ylyq\\src\\main\\resources\\lingo\\lingoproduct.lng";
//            String path = "lingo/lingoproduct.lng";
//            File resultFile = iLingoService.excuteLingo(parms.toString(), path);
//            if (resultFile != null) {
//                Wini inifile = new Wini(resultFile);
//                String result = inifile.get("result", "chanpin");
//            }


            StringBuilder parmsBudgt = new StringBuilder();
            parmsBudgt.append("100~\n");

            String plan = "OCPM_" + Tools.getCurrentDate("yyyyMMdd_HH_mm") + "_" + (1);//计划的名称，也对应执行lingobid的输出文件的取名
//                    String pathBid = ResourceUtils.getURL("classpath:").getPath().replace("/target/classes", "") + "\\src\\main\\resources\\lingo\\lingobid.lng";
//                    String pathBid = System.getProperty("user.dir")+ "\\ylyq\\src\\main\\resources\\lingo\\lingobid.lng";;
            String pathBid = "lingo/lingobid.lng";

            File resultFileBid = iLingoService.excuteLingo(parmsBudgt.toString(), pathBid, plan);
            if (resultFileBid != null) {
                Wini iniBid = new Wini(resultFileBid);
                double chujia = Double.parseDouble(iniBid.get("jieguo", "chujia"));
                double rys = Double.parseDouble(iniBid.get("jieguo", "rys"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @PostMapping("/testLingo1")
    @ApiOperation(value = "testLingo1", response = ResultPlan.class)
    public ResponseData testLingo1() {
        try {
            StringBuilder parms = new StringBuilder();
            parms.append("1801~\n");
            parms.append("7~\n");

            //产品定价 高 高中 中端 中低 低
            parms.append("3~\n");
            //获取产品打分值
//                String path = ResourceUtils.getURL("classpath:").getPath().replace("/target/classes", "") + "\\src\\main\\resources\\lingo\\lingoproduct.lng";
//                String path = System.getProperty("user.dir")+ "\\ylyq\\src\\main\\resources\\lingo\\lingoproduct.lng";
            String path = "lingo/lingoproduct.lng";
            File resultFile = iLingoService.excuteLingo(parms.toString(), path);
            if (resultFile != null) {
                Wini inifile = new Wini(resultFile);
                String result = inifile.get("result", "chanpin");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @PostMapping("/testPage")
    @ApiOperation(value = "testPage", response = ResultPlan.class)
    public ResponseData testPage() {
        QueryWrapper<YlyqCreativeTitleV2> titleV2QueryWrapper = new QueryWrapper<>();
        titleV2QueryWrapper.eq("advertise_id", 1672883265388557l);
        titleV2QueryWrapper.eq("group_name", "111120200917_15:53");
        titleV2QueryWrapper.select("title_name", "id");
        titleV2QueryWrapper.orderByAsc("RAND()");
//        List<Object> objectsTitles = iYlyqCreativeTitleV2Service.listObjs(titleV2QueryWrapper);
//        List<Object> objectsTitles =iYlyqCreativeTitleV2Service.page(new Page<>(1, 10),titleV2QueryWrapper).getRecords();
        List<YlyqCreativeTitleV2> objectsTitles = iYlyqCreativeTitleV2Service.page(new Page<>(1, 10), titleV2QueryWrapper).getRecords();


        iYlyqCreativeTitleV2Service.page(new Page<>(1, 10), titleV2QueryWrapper).getRecords();


        int size = objectsTitles.size();
        return new ResponseData(ResponseData.Result.SUCCESS, objectsTitles);
    }

}
